<script setup lang="ts">
import {computed, ref} from "vue";
import {Comment, Edit, Search} from '@element-plus/icons-vue'
import {ElNotification, FormInstance, FormRules, ElMessage} from "element-plus";
import mainIcon from '/src/assets/images/logo.svg';
import axios from "axios";
import {v4 as uuidv4} from "uuid";
import {ServerHost, loginUser} from "@/main";

const sendQuestionTitle = ref("")
const sendQuestionContent = ref("")
const isShowPostQuestionDialog = ref(false)
const onClickPostQuestion = () => {
  if (!sendQuestionTitle.value) {
    ElMessage.error("请输入问题")
    return
  }
  isShowPostQuestionDialog.value = true
}

const onSubmitQuestion = () => {
  if (!sendQuestionTitle.value) {
    ElMessage.error("请输入问题")
    return
  }
  const newQuestion = {
    id: uuidv4(),
    title: sendQuestionTitle.value,
    content: sendQuestionContent.value,
    user: loginUser.value.id,
    date: new Date(),
  }
  axios.post(`${ServerHost}/postNewQuestion`, newQuestion)
      .then(res => {
        if (res.status === 200) {
          ElNotification({
            title: '已发布问题，请等待回答',
            type: 'success',
            position: 'bottom-right',
          })
          // 清空内容，关闭弹窗
          isShowPostQuestionDialog.value = false
          sendQuestionTitle.value = ""
          sendQuestionContent.value = ""
          loadList()
        } else {
          ElNotification({
            title: '发布失败，请稍后重试',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

const questionList = ref([])
// 获取问题列表（不包括用户自己的提问）
const loadList = () => {
  questionList.value = []
  axios.get(`${ServerHost}/getQuestionList?isIncludeOwn=true`).then((res) => {
    if (res.status === 200) {
      console.log(res.data)
      questionList.value = res.data
      //   获取问题的回答列表
      questionList.value.forEach(q => {
        axios.get(`${ServerHost}/getAnswerListByQid?qId=${q.id}`).then((res) => {
          if (res.status === 200) {
            q.answerList = res.data
            console.log(q.answerList.length)
            // 获取提问的用户信息
            axios.get(`${ServerHost}/getUser?id=${q.user}`).then((res) => {
              if (res.status === 200) {
                q.user = res.data
              }
            })
            //   获取回答的用户信息
            q.answerList.forEach(a => {
              axios.get(`${ServerHost}/getUser?id=${a.user}`).then((res) => {
                if (res.status === 200) {
                  a.user = res.data
                }
              })
            })
          }
        })
      })
      console.log(questionList.value)
    }
  })
}
loadList()

const filterTableData = computed(() =>
    questionList.value.filter(q => {
      return q.title.includes(sendQuestionTitle.value) || // 检索问题标题
          q.content.includes(sendQuestionTitle.value) || // 检索问题内容
          q.answerList.some((answer: any) => answer.content.includes(sendQuestionTitle.value))  // 检索问题所有回答的内容
    })
)

const isShowAnswerDialog = ref(false)
const selectedQuestion = ref({})
const answerText = ref("")
const onClickAnswerTA = (e: Event, q: any) => {
  e.stopPropagation()
  selectedQuestion.value = q
  isShowAnswerDialog.value = true
}

const onSubmitAnswer = () => {
  if (!answerText.value) {
    ElMessage.error("请输入回答内容")
    return
  }
  const newAnswer = {
    id: uuidv4(),
    qId: selectedQuestion.value.id,
    content: answerText.value,
    user: loginUser.value.id,
    date: new Date(),
  }
  axios.post(`${ServerHost}/postNewAnswer`, newAnswer)
      .then(res => {
        if (res.status === 200) {
          ElNotification({
            title: '回答成功',
            type: 'success',
            position: 'bottom-right',
          })
          isShowAnswerDialog.value = false
          loadList()
        } else {
          ElNotification({
            title: '回答失败，请稍后重试',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

const isShowQDetailsDialog = ref(false)
const onClickQ = (q: any) => {
  selectedQuestion.value = q
  isShowQDetailsDialog.value = true
  return false
}
</script>

<template>
  <div class="flex flex-col items-center justify-center w-full gap-2 mt-2 mb-2">
    <el-image class="consult-ico" :src="mainIcon" alt="咨询"/>
    <el-input class="send-q-input m-2" v-model="sendQuestionTitle" placeholder="想问些什么？">
      <template #prepend>
        <el-button :icon="Search"/>
      </template>
      <template #append>
        <el-button @click="onClickPostQuestion">问大家</el-button>
      </template>
    </el-input>

    <div style="width: 80%;">
      <div class="question-list">
        <div v-for="question in filterTableData" @click="onClickQ(question)">
          <el-card class="question-item">
            <div class="flex justify-between items-center">
              <div class="flex">
                <el-tag v-if="question.user.isAdmin" class="mr-1">管理员</el-tag>
                <p>{{ question.title }}</p>
              </div>
              <el-button @click="onClickAnswerTA($event, question)">
                回答TA
                <el-icon class="el-icon--right">
                  <Comment/>
                </el-icon>
              </el-button>
            </div>
            <div v-for="answer in question.answerList">
              <p class="answer-content"><span class="answer-username">{{
                  answer.user.username
                }}</span>：{{ answer.content }}</p>
            </div>
            <p v-if="question.answerList != null && question.answerList.length == 0">暂无回答</p>
          </el-card>
        </div>
      </div>
    </div>
  </div>

  <!-- Post Question Dialog -->
  <el-dialog
      v-model="isShowPostQuestionDialog"
      title="问大家">
    <div>
      <el-form>
        <el-form-item label="问题标题">
          <el-input
              v-model="sendQuestionTitle"
              placeholder="请输入问题描述">
          </el-input>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input
              v-model="sendQuestionContent"
              placeholder="请输入问题描述"
              type="textarea"
              :rows="6">
          </el-input>
        </el-form-item>
        <el-button type="primary" @click="onSubmitQuestion">提交问题</el-button>
      </el-form>
    </div>
  </el-dialog>

  <!-- Q Details Dialog -->
  <el-dialog
      v-model="isShowQDetailsDialog"
      :title="selectedQuestion.title">
    <div>
      <p>{{ selectedQuestion.content }}</p>
      <div v-for="answer in selectedQuestion.answerList">
        <p><span class="answer-username">{{
            answer.user.username
          }}</span>：{{ answer.content }}</p>
      </div>
      <p v-if="selectedQuestion.answerList != null && selectedQuestion.answerList.length == 0">暂无回答</p>
    </div>
  </el-dialog>

  <!-- Answer Dialog -->
  <el-dialog
      v-model="isShowAnswerDialog"
      title="回答TA">
    <div>
      <el-form>
        <el-form-item label="问题标题">
          <p>{{ selectedQuestion.title }}</p>
        </el-form-item>
        <el-form-item label="回答内容">
          <el-input
              v-model="answerText"
              placeholder="请输入回答内容"
              type="textarea"
              :rows="6">
          </el-input>
        </el-form-item>
        <el-button type="primary" @click="onSubmitAnswer">确认并回答TA</el-button>
      </el-form>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.consult-ico {
  width: 120px;
}

.send-q-input {
  width: 80%;
}

.question-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  place-self: center;
}

.question-item {
  width: 100%;
}

.answer-content {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.answer-username {
  color: var(--el-color-primary);
}
</style>
